home *** CD-ROM | disk | FTP | other *** search
/ Magnum One / Magnum One (Mid-American Digital) (Disc Manufacturing).iso / d12 / cbibcode.arc / BSEARCH.C < prev    next >
Encoding:
Text File  |  1991-08-05  |  1.4 KB  |  43 lines

  1. /* bsearch on page 312 of the Turbo C Bible */
  2. #include <stdio.h>
  3. #include<string.h>
  4. #include <stdlib.h>
  5. int mycompare(const void *, const void *);
  6. main(int argc, char **argv, char **envp)
  7. {
  8.    unsigned int i, count;
  9.    char **p_table, **result;
  10.    if(argc <2)
  11.    {
  12.       printf("Usage: %s <KEYWORD>\n", argv[0]);
  13.       exit(0);
  14.    }
  15.                        /* Find length of environment table */
  16.    for(count = 0, p_table = envp;
  17.       *p_table !=NULL;
  18.       p_table++, count++);             /* a null loop */
  19.                        /* Sort the environment table using "qsort" */
  20.    qsort((void *) envp, (size_t)count,
  21.      (size_t)sizeof(char *), mycompare);
  22.                        /* Print sorted environment table */
  23.    printf("=+=== Sorted environment table =====\n");
  24.    for(i = 0, p_table = envp; i < count; i++)
  25.    {
  26.       printf("%s\n", *p_table);
  27.       p_table++;
  28.    }
  29.                        /* Search for the KEY variable i the environment */
  30.    result = (char **) bsearch((const void *)&argv[1], (const void *)envp,
  31.                   (size_t)count, (size_t)sizeof(char *),
  32.                   mycompare);
  33.    if(result != NULL)
  34.       printf("\nFound %s in\n%s\n", argv[1], *result);
  35.    else
  36.       printf("\n%s not found. Try with uppercase keyword\n", argv[1]);
  37. }
  38.                        /* ------------------------------ */
  39. int mycompare(const void *arg1, const void *arg2)
  40. {
  41.                /* Compare two strigs up to the length of the key */
  42.    return(strncmp(*(char**)arg1, *(char**)arg2, strlen(*(char**)arg1)));
  43. }